package com.example.dingtalklogin.adpter.web.controller;

import com.example.dingtalklogin.common.config.DingtalkProperties;
import com.example.dingtalklogin.common.util.UserUtil;
import com.example.dingtalklogin.service.LoginService;
import com.example.dingtalklogin.service.dto.DingtalkUnBindingCmd;
import com.example.dingtalklogin.service.dto.UserLoginCmd;
import com.example.dingtalklogin.service.dto.data.UserDto;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

/**
 * 登录相关逻辑控制器
 * @author xuzhen97
 */
@Controller
public class LoginController {

    @Resource
    private LoginService loginService;
    @Resource
    private DingtalkProperties dingtalkProperties;

    /**
     * 登录页面，path保存跳转链接
     * @param path
     * @return
     */
    @GetMapping("/login")
    public ModelAndView login(String path){
        ModelAndView mav = new ModelAndView("login");

        mav.addObject("path", path);
        mav.addObject("dingtalk", dingtalkProperties);

        return mav;
    }

    /**
     * 解绑钉钉
     * @return
     */
    @GetMapping("/unbinding-dingtalk")
    public ModelAndView unBindingDingtalk(){
        UserDto userDto = UserUtil.getCurrUser();
        DingtalkUnBindingCmd cmd = new DingtalkUnBindingCmd();
        cmd.setUserId(userDto.getId());
        cmd.setOpUserId(userDto.getId());
        loginService.unBindingDingtalk(cmd);
        //清理登录状态
        UserUtil.setCurrUser(null);
        ModelAndView mav = new ModelAndView("redirect:/login");
        return mav;
    }

    /**
     * 注销逻辑
     * @return
     */
    @GetMapping("/logout")
    public ModelAndView logout(){
        // 清楚登录状态，到登录页
        UserUtil.setCurrUser(null);
        ModelAndView mav = new ModelAndView("redirect:/login");
        return mav;
    }

    /**
     * 登录表单提交
     * @param username
     * @param password
     * @param path
     * @return
     */
    @PostMapping("/login")
    public ModelAndView loginPost(@RequestParam String username
            , @RequestParam String password
            , String path){

        UserLoginCmd cmd = new UserLoginCmd();
        cmd.setUsername(username);
        cmd.setPassword(password);
        // 验证登录逻辑，保存登录状态
        UserDto loginUser = loginService.login(cmd);

        UserUtil.setCurrUser(loginUser);

        // 如果path为空则登录完成之后跳转到首页
        // path是你在访问需要登录后可见的页面的时候记录的url
        // ，方便登录后直接到我们想要的地址
        if(!StringUtils.hasLength(path)){
            path = "/";
        }

        ModelAndView mav = new ModelAndView("redirect:" + path);
        return mav;
    }
}
